#! /usr/bin/env python2  
# encoding=utf-8
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
import os
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
import xmlrpclib
import ConfigParser
import datetime

# 更新电梯上的计算数据
# 投诉数量 报修数量 救援数量 定检数量
# er:
# compliant_count = fields.Integer(string=u"投诉数量")
# repair_count = fields.Integer(string=u"报修数量")
# save_count = fields.Integer(string=u"救援数量")

config = ConfigParser.RawConfigParser()
config.read(ScriptPath+'/sys.cfg')
url = config.get('odoo','host')
uid = 1
pwd = config.get('odoo','password')
db = config.get('odoo','db')
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))


"""
返回值：
    [
        {
            'lift_id_count':2,'lift_id':[id,name],'__domain':[['lift_id','=',id]]
        }
    ]
"""
def group_by(model):
    countModel = models.execute_kw(db,uid,pwd,model,'read_group',[[]],{'fields':['lift_id','id'],'groupby':'lift_id'})
    return countModel


def upCount(lifts,field,counts):
    for count in counts:
        lift_id = count['lift_id'][0]
        for lift in lifts:
            if lift['id'] == lift_id:
                if lift[field] != count['lift_id_count']:
                    print u"更新电梯"+str(lift['id'])+":"+field
                    models.execute_kw(db,uid,pwd,'tyibs.base.lift','write',
                        [[lift['id']],{field:count['lift_id_count']}]
                    )


def main():
    print u"开始更新电梯计算字段"
    lifts = models.execute_kw(db,uid,pwd,'tyibs.base.lift','search_read',[[]],{'fields':['compliant_count','repair_count','save_count']})
    # 投诉
    upCount(lifts,'compliant_count',group_by('tyibs.er.work.order.compliant'))
    # 报修
    upCount(lifts,'repair_count',group_by('tyibs.er.work.order.repair'))
    # 救援
    upCount(lifts,'save_count',group_by('tyibs.er.work.order.save'))


if __name__ == '__main__':
    main()